// 2013-7-30上午12:15:08  net.betou.core.service.impl.NewsPostDataListener.java

package net.betou.core.service.impl;

import java.util.Map;

import net.betou.common.util.DateUtils;
import net.betou.core.service.PostDataAbstract;
import net.betou.core.service.post.PostKeyVal;
import net.betou.trade.entity.main.AgentAndAdmins;
import net.betou.trade.entity.main.Content;

import org.apache.log4j.Logger;
import org.jsoup.Connection.KeyVal;
import org.springframework.stereotype.Component;

/**
 * 二、新闻发布
 * 格式：fenxi~!^$1~!^~!^$15~!^~!^$0~!^$5,6,7|@!@|新闻标题|@!@|新闻内容|@!@|发布时间|@!@|链接地址
 * 说明：fenxi+发布单位+机构ID+代理商ID+发布人id+用户组+新闻标题+新闻内容+发布时间+链接地址
 * 
 * @author 叶装装
 */
@Component
public class ContentPostDataListener extends PostDataAbstract< Content >{

	private static final Logger log = Logger.getLogger( ContentPostDataListener.class );
	
	@Override
	public void afterChange( Content bean, Map< String, Object > map ) {
		AgentAndAdmins admin = bean.getAdmin( );
		
		send( admin, bean );
		
	}

	/**
	 */
	public void afterSave( final Content bean ) {
		
		log.info( "保存新闻完毕，准备发送数据！" );

		final AgentAndAdmins admin = bean.getAdmin( );

		KeyVal key = new PostKeyVal( mng ){
			@Override
			public String processValue( ) {

				StringBuffer buffer = new StringBuffer( );

				boolean agency = admin.getAgency( );

				// 发布标识
				this.appendToBuffer( buffer, "fenxi" );
				// 发布单位
				this.appendToBuffer( buffer, agency ? 1 : 0 );

				Integer [ ] agencyProxy = getAgencyProxy( admin );
				// 机构ID
				this.appendToBuffer( buffer, agencyProxy[ 0 ] );

				// 代理商ID
				this.appendToBuffer( buffer, agencyProxy[ 1 ] );

				// 发布人用户名
				this.appendToBuffer( buffer, admin.getUsername( ) );
				// 面向用户组
				this.appendToBuffer( buffer, bean.getChannel( ).getOrientedGroup( ) );
				// 标题
				this.appendToBuffer( buffer, this.cleanHtml( bean.getTitle( ) ) ); // 标题为80个字符，所以这里不设置
				// 内容
				this.appendToBuffer( buffer, this.subString( this.cleanHtml( bean.getContent( ) ) ) );
				// 时间
				this.appendToBuffer( buffer, DateUtils.getStringOnFormat( bean.getPubDate( ), 1 ) );
				// 链接地址
				this.appendToBuffer( buffer, "/content/view.jhtml?id=" + bean.getId( ) );

				return buffer.toString( );

			}
		};

		post.setKeyVal( key );
		task.addTask( post );

		send( admin, bean );
	}
	
	private void send( AgentAndAdmins admin, Content bean ){
		
		// 不发送
		if( !bean.getSend( ) ){
			return;
		}

		String smsGroup = bean.getChannel( ).getSmsGroup( );
		
		boolean validate = validateSmsSend( smsGroup, bean.getDescription( ) );
		
		if( !validate ){
			return;
		}

		smsPost.setAdmin( admin );
		smsPost.setContent( clearHtml( bean.getDescription( ) ) );
		smsPost.setSmsGroups( smsGroup );

		task.addTask( smsPost );
	}

}
